package com.hanqian.zebra.util;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.hanqian.zebra.other.AjaxResult;

import javax.imageio.ImageIO;
import javax.imageio.stream.ImageOutputStream;
import javax.print.*;
import javax.print.attribute.DocAttributeSet;
import javax.print.attribute.HashDocAttributeSet;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
import javax.print.attribute.standard.MediaPrintableArea;
import javax.print.attribute.standard.PrinterName;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;

import static com.google.zxing.client.j2se.MatrixToImageWriter.toBufferedImage;

/**
 * zebra打印
 * ============================================================================
 * author : dzw
 * createDate:  2020/6/24 。
 * ============================================================================
 */
public class ZebraUtil {

	/**
	 * 执行打印
	 * @param printerURI zebra打印机名称
	 * @param no 固定资产编码
	 * @param type 打印的纸张类型（1：大的    2：小的）
	 * @return result
	 */
	public static AjaxResult print(String printerURI, String no, Integer type, String url,String name) throws Exception {
		if(StrUtil.isBlank(printerURI) || StrUtil.isBlank(no) || StrUtil.isBlank(url)){
			return AjaxResult.error("参数存在空值");
		}
		if(type!=1 && type!=2){
			return AjaxResult.error("type fail");
		}

		//打印机服务
		PrintService defaultService = null;
		// 构建打印请求属性集
		PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
		// 设置打印格式
		DocFlavor flavor = DocFlavor.INPUT_STREAM.JPEG;
		// 查找所有的可用的打印服务
		PrintService[] printServices = PrintServiceLookup.lookupPrintServices(flavor, pras);
		if (printServices != null && printServices.length > 0) {
			for (PrintService service : printServices) {
				if (printerURI.equals(service.getName())) {
					defaultService = service;
					break;
				}
			}
		}

		if (defaultService == null) {
			System.out.println("没有找到打印机：["+printerURI+"]");
			System.out.println("可用的打印机列表：");
			String findPrintNames = "";
			for (PrintService service : printServices) {
				System.out.println("["+service.getName()+"]");
				findPrintNames+=service.getName() + "。";
			}
			return AjaxResult.error("没有找到打印机：["+printerURI+"]。可用列表：【"+findPrintNames+"】");
		}else{
			System.out.println("找到打印机：["+printerURI+"]");
			System.out.println("打印机名称：["+defaultService.getAttribute(PrinterName.class).getValue()+"]");
		}

		// 获得打印工作
		DocPrintJob job = defaultService.createPrintJob();
		DocAttributeSet das = new HashDocAttributeSet();
		das.add(new MediaPrintableArea(0, 0, 100,500, MediaPrintableArea.INCH ));
		// 设置打印内容
		ByteArrayInputStream bais = type==1 ? getPrintSteamOfBig(no,url,name) : getPrintSteamOfSmall(no,url,name);
		Doc doc = new SimpleDoc(bais, flavor, das);
		// 开始打印
		job.print(doc, pras);
		bais.close();

		return AjaxResult.success("打印成功");
	}

	//构建打印对象（大的）
	private static ByteArrayInputStream getPrintSteamOfBig(String code, String url, String name) throws Exception {
		// 在内存中创建图象
		int width = 1300, height = 1400;
		BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
		Graphics g = image.getGraphics();
		g.setColor(new Color(255, 255, 255));
		g.drawRect(0, 0, width, height);
		g.fillRect(0, 0, width+1, height+1);
		g.setFont(new Font("楷体", Font.BOLD, 100));
		g.setColor(new Color(0, 0, 0));

		//编码的x轴位置
		int codeX = 50;
		if(code.length()<10){
			codeX = 275;
		}else if(code.length()<15){
			codeX = 175;
		} else if(code.length()<20){
			codeX = 100;
		}

		//二维码
		QRCodeWriter qrCodeWriter = new QRCodeWriter();
		BitMatrix bitMatrix = qrCodeWriter.encode(url, BarcodeFormat.QR_CODE, 1100, 1100);
		BufferedImage qrImage = toBufferedImage(bitMatrix);

		g.drawImage(qrImage, 45, 170, 900, 900, null);
		g.drawString("胸科医院固定资产", 75, 220);
		g.setFont(new Font("楷体", Font.BOLD, 80));
		g.drawString(code, codeX, 1070);
		g.setFont(new Font("微软雅黑", Font.PLAIN, 100));
		if(name.length() > 8){
			g.drawString(name.substring(0,8), 220, 1200);
		}else{
			g.drawString(name, 220, 1200);
		}
//		g.drawString("质控", 420, 1200);
//		g.drawString("盘点", 620, 1200);

		// 图象生效
		g.dispose();
		ByteArrayOutputStream output = new ByteArrayOutputStream();
		ImageOutputStream imageOut = ImageIO.createImageOutputStream(output);
		ImageIO.write(image, "JPEG", imageOut);
		imageOut.close();
		ByteArrayInputStream input = new ByteArrayInputStream(output.toByteArray());
		return input;
	}

	//构建打印对象（小的）
	public static ByteArrayInputStream getPrintSteamOfSmall(String code, String url, String name) throws Exception{

		// 在内存中创建图象
		int width = 1300, height = 1200;
		BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
		Graphics g = image.getGraphics();
		g.setColor(new Color(255, 255, 255));
		g.drawRect(0, 0, width, height);
		g.fillRect(0, 0, width+1, height+1);
		g.setFont(new Font("微软雅黑", Font.BOLD, 62));
		g.setColor(new Color(0, 0, 0));

		int codeX = 15;
		if(code.length()<10){
			codeX = 160;
		}else if(code.length()<15){
			codeX = 95;
		} else if(code.length()<20){
			codeX = 35;
		}

		//二维码
		QRCodeWriter qrCodeWriter = new QRCodeWriter();
		BitMatrix bitMatrix = qrCodeWriter.encode(url, BarcodeFormat.QR_CODE, 545, 545);
		BufferedImage qrImage = toBufferedImage(bitMatrix);

		g.drawImage(qrImage, 520, -50, 500, 500, null);
		g.drawString("胸科医院固定资产", 20, 80);
		g.setFont(new Font("微软雅黑", Font.BOLD, 42));
		g.drawString(code, codeX, 200);
		g.setFont(new Font("微软雅黑",  Font.PLAIN, 55));
		if(name.length() > 8){
			g.drawString(name.substring(0,8), 35, 290);
			g.drawString(name.substring(8,name.length() > 16 ? 16 : name.length()), 35, 350);
		}else{
			if(name.length() < 4){
				g.drawString(name, 200, 350);
			}else{
				g.drawString(name, 100, 350);
			}
		}
//		g.drawString("质控", 215, 350);
//		g.drawString("盘点", 395, 350);

		// 图象生效
		g.dispose();
		ByteArrayOutputStream output = new ByteArrayOutputStream();
		ImageOutputStream imageOut = ImageIO.createImageOutputStream(output);
		ImageIO.write(image, "JPEG", imageOut);
		imageOut.close();
		ByteArrayInputStream input = new ByteArrayInputStream(output.toByteArray());

//		ImageIO.write(image, "JPEG", FileUtil.file("D:/test.jpg"));

		return input;
	}

}
